package nsoft.timeline.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class audio {
	static int MAX_FILE_SIZE = 5 * 1024 * 1024;
	static int MAX_MEM_SIZE = 5 * 1024 * 1024;
	static String SPLITTER = "<nsoft_splitter>";
	static String INLINE_SPLITTER = "<nsoft_inline_splitter>";
	static String PRIME = "<nsoft_prime>";
	static String DOUBLE_PRIME = "<nsoft_dprime>";
	static String TEMP_PATH = "temp";
	static String TEMP_THUMB_PATH = "thumb";
	static String EXT_ARRAY = "mp3";
	static int STD_IMAGE_WIDTH = 920;
	static int STD_IMAGE_HEIGHT = 460;

	/**
	 * delete an audio file requested from client
	 * @param req
	 * @param resp
	 */
	public static void delete(HttpServletRequest req, 
							HttpServletResponse resp){
		
	}
	
	/**
	 * upload an audio file request from client
	 * @param req
	 * @param resp
	 */
	public static void upload(HttpServletRequest req, 
							HttpServletResponse resp){
		String contentType = req.getContentType();
		String tempPath = System.getProperty("wtp.deploy") + 
								"/timeline/" + TEMP_PATH;
		String thumbPath = tempPath + "/" + TEMP_THUMB_PATH;
		
		boolean isPathExist = new File(tempPath).exists();
		if (!isPathExist){
			new File(tempPath).mkdir();
			new File(thumbPath).mkdir();
		}
		
		String output = "";
		PrintWriter out = null;
		try{
			out = resp.getWriter();
		}catch(IOException ioEx){
			System.err.println(ioEx.getClass() + ": " + ioEx.getMessage());
		}
		if (out == null) {
			System.err.println("server is not responsible.");
			return;
		}
		
        if ((contentType != null) && 
        		(contentType.indexOf("multipart/form-data") >= 0)){
        	DiskFileItemFactory factory = new DiskFileItemFactory();
        	factory.setSizeThreshold(MAX_MEM_SIZE);
        	
        	ServletFileUpload upload = new ServletFileUpload(factory);
        	upload.setFileSizeMax(MAX_FILE_SIZE);
        	
        	@SuppressWarnings("rawtypes")
        	List fileItems = null;
        	try {
        		fileItems = upload.parseRequest(req);
        	}catch(FileUploadException fuEx){
        		String error = fuEx.getClass() + ": " + fuEx.getMessage();
        		System.err.println(error);
        		output = "0" + SPLITTER + error + SPLITTER + SPLITTER + "0";
        	}
        	
        	if (fileItems != null){
	        	FileItem fi = (FileItem)fileItems.iterator().next();
	        	if (!fi.isFormField()){
	        		String fileName = fi.getName();
	        		String ext = fileName.substring(fileName.lastIndexOf("."));
	        		String newFilename = UUID.randomUUID().toString() + ext;
	        		/*
	        		long sizeInBytes = fi.getSize();
	        		*/
	        		String filepath = tempPath + "/" + newFilename;
	        		File file = new File(filepath);
	
	        		try {
	        			fi.write(file);
	        			String[] data=createAudioThumb(filepath, thumbPath).split(SPLITTER);
	        			String newThumbFile =data[0]; 
	        			String newThumbFileName = new File(newThumbFile).getName();
	        			
	        			output = "1" + SPLITTER + 
	        				"./" + TEMP_PATH + "/" + TEMP_THUMB_PATH + 
	        						"/" + newThumbFileName +SPLITTER + 
	        				"./" + TEMP_PATH + "/" + newFilename + SPLITTER + 
	        				data[1].trim();
	        		}catch(Exception ex){
	        			String error = ex.getClass() + ": " + ex.getMessage();
	        			System.err.println(error);
	        			output = "100" + SPLITTER + error + SPLITTER + SPLITTER + "0";
	        		}
	        	} 
            }

        	out.println(output);
        	out.flush();
        	
        	out.close();
        }else{
        	System.err.println("content-type is null due to a problem at server");
        }
	}
	
	private static String createAudioThumb(String file, 
						String thumbPath) throws Exception{
		StringBuilder ret=new StringBuilder();
		String filePro=file.replace('\\', '/');
		mp3info mp3obj=new mp3info(filePro);
		ret.append(mp3obj.createImage(950, 50, thumbPath))
			.append(SPLITTER)
			.append(mp3obj.getAudioFormat(INLINE_SPLITTER));
		return ret.toString();
	}
}
